/*
    Copyright (C) 2015 Apple Inc. All Rights Reserved.
    See LICENSE.txt for this sample’s licensing information
    
    Abstract:
    A table view controller that displays filtered strings based on callbacks from a UISearchController.
*/

import UIKit

class SearchResultsViewController: SearchControllerBaseViewController, UISearchResultsUpdating {
    // MARK: Types
    
    @IBOutlet weak var searchNum: UILabel!
    var dataArr:NSMutableArray = []
    var imageArr:NSMutableArray = []
    var hitArr:NSMutableArray = []
    var lessonidArr:NSMutableArray = []
    var courseArr = NSArray()
    var itemList:AllCourseItem! = nil
    var totalcount = 0
    var lineImageView:UIImageView! = nil
    struct StoryboardConstants {
        /// The identifier string that corresponds to the SearchResultsViewController's view controller defined in the main storyboard.
        static let identifier = "SearchResultsViewControllerIdentifier"
    }
    
    // MARK: UISearchResultsUpdating
    
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        // updateSearchResultsForSearchController(_:) is called when the controller is being dismissed to allow those who are using the controller they are search as the results controller a chance to reset their state. No need to update anything if we're being dismissed.
       
        /*
        if !searchController.active {
            return
        }
        
        filterString = searchController.searchBar.text
        //println(filterString)
        */
         filterString = searchController.searchBar.text

        if(filterString != "")
        {
            searchResult()
        }
    }
    
    func searchResult() {
        var userid:Int = 1
        var keyword:String = filterString!
        NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLLessonList() , parameters: ["keyword":keyword], responseHandler: nil, netErrorHandler: nil, successHandler: searchResultHandle, interErrorHandler: nil, jsonErrorHandler: nil)
    }
    func searchResultHandle(json: JSON) {
        
        
       
       // totalcount = json["totalcount"].int!
        totalcount = json["list"].count

        dataArr.removeAllObjects()

        for (var i = 0;i < totalcount ; i++ )
        {
            
            json["list"][i]["lessonname"].string!
            
            dataArr.addObject(json["list"][i]["lessonname"].string!)
            imageArr.addObject(json["list"][i]["imgurl"].string!)
           
            hitArr.addObject(json["list"][i]["hit"].int!)
            lessonidArr.addObject(json["list"][i]["lessonid"].int!)
            
        }
        self.tableView.reloadData()
        
       }
    
    func baseResult(str: String){
    var userid:Int = 1
    var keyword:String = str
    NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLLessonList() , parameters: ["keyword":keyword], responseHandler: nil, netErrorHandler: nil, successHandler: searchResultHandle, interErrorHandler: nil, jsonErrorHandler: nil)
  
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //return visibleResults.count

        return dataArr.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //return tableView.dequeueReusableCellWithIdentifier("AllCourseItem2", forIndexPath: indexPath) as! UITableViewCell NSLog("******************\(tableView)tb")
         
            searchNum.text = "共找到\(totalcount)个相关内容"
        var tableCell :AllCourseItem = tableView.dequeueReusableCellWithIdentifier("AllCourseItem2") as! AllCourseItem
        var s = dataArr.objectAtIndex(indexPath.row) as? String

        tableCell.courseName.text = s
        tableCell.starImage.image = UIImage(named: "星级.png")
        var str = hitArr.objectAtIndex(indexPath.row) as! Int
        tableCell.numOfPeople.text = "\(String(str))人在学"
        tableCell.accessoryType = UITableViewCellAccessoryType.None
        var url:String = imageArr.objectAtIndex(indexPath.row) as! String
        


        DBUtils.getImageFromFile(url, successHandler: { (imgUrl, img) -> Void in
            if (url == imgUrl) {
                tableCell.courseImage.image = img
            }
        })

        return tableCell

        
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        //cell.textLabel!.text = visibleResults[indexPath.row]
       // cell.textLabel!.text = allResults1[indexPath.row]
    }
  
    
     override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        var allcoursedetail = UIStoryboard(name: "AllCourse", bundle: nil).instantiateViewControllerWithIdentifier("AllCourseDetail") as! AllCourseDetail
        rootController.navigationController?.pushViewController(allcoursedetail, animated: true)
        allcoursedetail.isFirstPage = false
        allcoursedetail.lessonId =  lessonidArr.objectAtIndex(indexPath.row) as? Int

        allcoursedetail.lessonName = dataArr.objectAtIndex(indexPath.row) as! String
    
    }
    
//add by py
    
//添加表格底部按钮
    
    /*
    override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))
        footerView.backgroundColor = UIColor.blackColor()
        
        return footerView
    }
    
    override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 40.0
    }
    
    */
    
}
